﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CPPEI.Coolzon.ServiceProxy.DataServiceRef;
using System.Windows.Media.Animation;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// Interaction logic for DataDigitalAnimationLabel.xaml
    /// </summary>
    [System.ComponentModel.DisplayName("数字动画标签")]
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/数字动画.png")]
    public partial class DataDigitalAnimationLabel : DataAnimationLabelBase
    {
        private Storyboard _animationStoryboard;

        public DataDigitalAnimationLabel()
        {
            XMoveTimeType = "PerDigit";
            XDataSeriesId = "series1";
            XDataItemId = "data1";
            XFontSize = 20;
            SetDefaultDataResult();
            InitializeComponent();
        }
        protected virtual void SetDefaultDataResult()
        {
            Random random = new Random();
            ServiceProxy.DataServiceRef.DataSeries[] series = new ServiceProxy.DataServiceRef.DataSeries[1];
            ServiceProxy.DataServiceRef.DataItem[] tmpItems = new ServiceProxy.DataServiceRef.DataItem[5];
            for (int i = 1; i <= 5; i++)
            {
                tmpItems[i - 1] = new ServiceProxy.DataServiceRef.DataItem();
                tmpItems[i - 1].Id = "data" + i;
                tmpItems[i - 1].Name = "data" + i;
                tmpItems[i - 1].Value = (random.NextDouble() * 250).ToString("F2");
            }
            series[0] = new ServiceProxy.DataServiceRef.DataSeries();
            series[0].DataItems = tmpItems;
            series[0].Id = "series1";
            series[0].Name = "series1";
            DataResult = new ServiceProxy.DataServiceRef.DataResult();
            DataResult.DataSeries = series;
        }

        #region Constructor

        protected override void OnActive(PartContext context)
        {
            base.OnActive(context);
        }
        protected override void OnDeactive(PartContext context)
        {
            OnDestory();
        }
        protected override void OnDestory()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
            gdLayout.Children.Clear();
            base.OnDestory();
        }
        protected override void OnApplyXProperty()
        {
            base.OnApplyXProperty();

            if (gdLayout == null || !IsInitiated) return;

            if (XDataSource == null)
            {
                DataItem dataItem = new DataItem();
                dataItem.Name = "北京";
                dataItem.Value = "100.90";

                OnDataItemBinding(dataItem);
            }
        }
        protected override void OnDataItemBinding(ServiceProxy.DataServiceRef.DataItem dataItem)
        {
            ClearAnimation();
            StopAnimation();
            _animationStoryboard = new Storyboard();
            _animationStoryboard.FillBehavior = FillBehavior.HoldEnd;
            _animationStoryboard.Completed += _animationStoryboard_Completed;

            gdLayout.Children.Clear();

            string itemValueString = string.Empty;
            if (!string.IsNullOrEmpty(XFormatString))
            {
                // 格式化处理结果
                if (XFormatString.ToUpper().Contains(":F"))
                {
                    double intValue = 0;
                    if (double.TryParse(dataItem.Value, out intValue))
                    {
                        itemValueString = string.Format(XFormatString, intValue);
                    }
                    else
                    {
                        itemValueString = dataItem.Value;
                    }
                }
                else if (XFormatString.ToUpper().Contains(":D"))
                {
                    int intValue = 0;
                    if (int.TryParse(dataItem.Value, out intValue))
                    {
                        itemValueString = string.Format(XFormatString, intValue);
                    }
                    else
                    {
                        itemValueString = dataItem.Value;
                    }
                }
            }
            else
            {
                itemValueString = dataItem.Value;
            }

            double animationInteval;
            if (!string.IsNullOrWhiteSpace(XMoveTimeType) && XMoveTimeType.ToUpper().Equals("PERDIGIT"))
            {
                animationInteval = (XDataAnimationDuration) / SumWithEveryNumber(itemValueString);
            }
            else
            {
                animationInteval = (XDataAnimationDuration) / (double)itemValueString.Replace(".", "").Length;
            }
            double beginTime = 0;

            double everyWidth = GetEveryCharWeight(itemValueString.Length);

            int startIndex = 0, endIndex = itemValueString.Length, offset = 1;
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            if (XFlowDirection != null && XFlowDirection.Equals("RightToLeft", StringComparison.OrdinalIgnoreCase))
            {
                sp.FlowDirection = FlowDirection.RightToLeft;
                startIndex = itemValueString.Length - 1;
                endIndex = -1;
                offset = -1;
            }
            sp.Width = Width;
            for (int i = startIndex; i != endIndex; i = i + offset)
            {
                char digital = itemValueString[i];
                Label lb = new Label();
                lb.Height = Height;
                lb.Width = everyWidth;
                lb.Margin = XLabelMargin;
                lb.ClipToBounds = true;

                if (!digital.Equals('.'))
                {
                    Canvas digitalCanval = new Canvas();
                    digitalCanval.Height = Height;
                    digitalCanval.Width = everyWidth;

                    ImageBrush imageBrush = new ImageBrush(XDigitalImage==null? null : XDigitalImage.ImageSource);
                    imageBrush.Stretch = Stretch.Fill;
                    digitalCanval.Background = imageBrush;

                    //添加0-9的数字,用于数字滚动动画
                    StackPanel spDigital = new StackPanel();
                    spDigital.Orientation = Orientation.Vertical;
                    //0-9,加一个最上面的空
                    spDigital.Height = 11 * Height;
                    spDigital.Width = everyWidth;

                    Canvas.SetTop(spDigital, 0);
                    Canvas.SetLeft(spDigital, 0);
                    for (int index = -1; index <= 9; index++)
                    {
                        //加强阴影效果，所以叠加3个
                        Grid shadowGrid = new Grid();
                        for (int shadowIndex = 1; shadowIndex <= 3; shadowIndex++)
                        {
                            Label lbContent = new Label();
                            InitControl(lbContent);
                            if (index != -1)
                            {
                                lbContent.Content = index.ToString();
                            }
                            lbContent.Width = everyWidth;
                            lbContent.Margin = XLabelPadding;
                            lbContent.Effect = GetDropShadowEffect();

                            shadowGrid.Children.Add(lbContent);
                        }
                        spDigital.Children.Add(shadowGrid);
                    }
                    digitalCanval.Children.Add(spDigital);

                    //动画
                    int intdigital = int.Parse(digital.ToString()) + 1;
                    DoubleAnimation animation;

                    if (!string.IsNullOrWhiteSpace(XMoveTimeType) && XMoveTimeType.ToUpper().Equals("PERDIGIT"))
                    {
                        animation = new DoubleAnimation(0, intdigital * Height * -1, new Duration(TimeSpan.FromSeconds(animationInteval * intdigital)));
                        animation.BeginTime = TimeSpan.FromSeconds(beginTime);
                        beginTime += animationInteval * intdigital;
                    }
                    else
                    {
                        animation = new DoubleAnimation(0, intdigital * Height * -1, new Duration(TimeSpan.FromSeconds(animationInteval)));
                        animation.BeginTime = TimeSpan.FromSeconds(animationInteval * i);
                    }
                    Storyboard.SetTarget(animation, spDigital);
                    Storyboard.SetTargetProperty(animation, new PropertyPath(Canvas.TopProperty));
                    _animationStoryboard.Children.Add(animation);

                    lb.Content = digitalCanval;
                }
                else
                {
                    InitControl(lb);
                    Canvas digitalCanval = new Canvas();
                    digitalCanval.Height = Height;
                    digitalCanval.Width = everyWidth;

                    ImageBrush imageBrush = new ImageBrush(XDigitalImage==null? null : XDigitalImage.ImageSource);
                    imageBrush.Stretch = Stretch.Fill;
                    digitalCanval.Background = imageBrush;
                    
                    TextBlock tb = new TextBlock();
                    tb.Text = digital.ToString();
                    digitalCanval.Children.Add(tb);
                    lb.Content = digitalCanval;
                }

                sp.Children.Add(lb);
            }
            gdLayout.Children.Add(sp);

            if (_animationStoryboard != null)
            {
                _animationStoryboard.Begin();
            }
        }

        /// <summary>
        /// 初始化控件属性
        /// </summary>
        private void InitControl(Label lb)
        {
            if (XFontSize != 0)
            {
                lb.FontSize = XFontSize;
            }
            lb.HorizontalContentAlignment = XTextAlign;
            lb.VerticalContentAlignment = XTextVAlign;
            if (XFont != null)
            {
                lb.FontFamily = XFont;
            }
            lb.FontWeight = XFontWeight;
            if (XForeground != null)
            {
                lb.Foreground = XForeground.Brush;
            }
            lb.Height = Height;
        }
        #endregion

        /// <summary>
        /// 获取各个位数加1的和(计算动画时间)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private int SumWithEveryNumber(string value)
        {
            int sum = 0;
            for (int i = 0; i < value.Length; i++)
            {
                char digital = value[i];
                if (!digital.Equals('.'))
                {
                    sum += int.Parse(digital.ToString()) + 1;
                }
            }
            return sum;
        }

        /// <summary>
        /// 动画完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _animationStoryboard_Completed(object sender, EventArgs e)
        {
            ClearAnimation();
        }

        /// <summary>
        /// 清理动画，清理故事版中每个动画的target，防止内存溢出
        /// </summary>
        private void ClearAnimation()
        {
            if (_animationStoryboard != null)
            {
                foreach (Timeline tl in _animationStoryboard.Children)
                {
                    tl.ClearValue(Storyboard.TargetProperty);
                }
            }
        }
        private void StopAnimation()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Completed -= _animationStoryboard_Completed;
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
        }
    }
}
